package com.sl.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.itheima.auth.factory.AuthTemplateFactory;
import com.itheima.auth.sdk.common.Result;
import com.itheima.auth.sdk.dto.AuthUserInfoDTO;
import com.itheima.auth.sdk.service.TokenCheckService;
import com.sl.gateway.config.MyConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 后台管理员token拦截处理
 */
@Component
public class ManagerTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> implements AuthFilter {

    @Resource
    private MyConfig myConfig;
    @Resource
    private TokenCheckService tokenCheckService;
    @Value("${role.manager}")
    private List<Long> managerRoles; //允许登录到管理系统的角色列表

    @Override
    public GatewayFilter apply(Object config) {
        //由于实现了AuthFilter接口，所以可以传递this对象到TokenGatewayFilter中
        return new TokenGatewayFilter(this.myConfig, this);
    }

    @Override
    public AuthUserInfoDTO check(String token) {
        //校验token
        return tokenCheckService.parserToken(token);
    }

    @Override
    public Boolean auth(String token, AuthUserInfoDTO authUserInfoDTO, String path) {
        //查用户角色信息，角色权限足够登录后台返回true 没权限就返回false
        //获取AuthTemplate对象
        Result<List<Long>> resultRole = AuthTemplateFactory.get(token).opsForRole()
//                获取该用户角色
                .findRoleByUserId(authUserInfoDTO.getUserId());
        //拿到角色列表 一个用户可能好几个角色
        List<Long> roles = resultRole.getData();
        //获取到两个集合的交集集合
        Collection<Long> intersection = CollUtil.intersection(roles, managerRoles);

        return CollUtil.isNotEmpty(intersection);
    }
}
